<template>
  <div>
    <el-row>
      <el-col :span="18">
        <div class="select-box">
          <el-form :inline="true" :model="selectData" class="demo-form-inline">
            <el-form-item label="学校名称">
              <el-input v-model="selectData.schoolName" placeholder="请输入学校名称" />
            </el-form-item>
            <el-form-item label="专业名称">
              <el-input v-model="selectData.profess" placeholder="请输入专业名称" />
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="onQuery">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col :span="6">
        <!-- <el-button type="primary" @click="addInfo" class="add-btn" style="float: right">添加</el-button> -->
      </el-col>
    </el-row>

    <div>
      <el-table border :data="infoTotalList" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="schoolCode" label="学校代码" />
        <el-table-column prop="schoolName" label="学校名称" />
        <el-table-column prop="province" label="省份" />
        <el-table-column prop="majorCode" label="专业代码" />
        <el-table-column prop="profess" label="专业名称" width="200" :show-overflow-tooltip="true" />
        <el-table-column prop="subject" label="专业类别" />
        <el-table-column prop="batch" label="录取批次" />
        <el-table-column prop="plan" label="招生人数" />
        <el-table-column fixed="right" label="操作" width="100">
          <template #default="scope">
            <el-button round type="primary" @click="editInfo(scope.row)">编辑</el-button>
            <!-- <el-button round type="danger" @click="deleteInfo(scope.row)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="currentChange" :current-page="currentPage" layout="prev, pager, next"
        :total="totalNum" background class="pagination" />
    </div>
    <div>
      <el-dialog v-model="isShow" :title="status === 0 ? '新增' : '编辑'" v-loading="isLoading">
        <el-form :model="activeData" inline :rules="rules" ref="formRef">
          <!-- <el-form-item label="ID" prop="id">
            <el-input placeholder="请输入ID" v-model.number="activeData.id" autocomplete="off" disabled />
          </el-form-item> -->
          <el-form-item label="学校代码" prop="schoolCode">
            <el-input placeholder="请输入学校代码" v-model="activeData.schoolCode" autocomplete="off" />
          </el-form-item>
          <el-form-item label="学校名称" prop="schoolName">
            <el-input placeholder="请输入学校名称" v-model="activeData.schoolName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="省份" prop="province">
            <el-input placeholder="请输入省份" v-model="activeData.province" autocomplete="off" />
          </el-form-item>
          <el-form-item label="专业代码" prop="majorCode">
            <el-input placeholder="请输入专业代码" v-model="activeData.majorCode" autocomplete="off" />
          </el-form-item>
          <el-form-item label="专业名称" prop="profess">
            <el-input placeholder="请输入专业名称" v-model="activeData.profess" autocomplete="off" />
          </el-form-item>
          <el-form-item label="专业类别" prop="subject">
            <el-input placeholder="请输入专业类别" v-model="activeData.subject" autocomplete="off" />
          </el-form-item>
          <el-form-item label="录取批次" prop="batch">
            <el-input placeholder="请输入录取批次" v-model.number="activeData.batch" autocomplete="off" />
          </el-form-item>
          <el-form-item label="招生人数" prop="plan">
            <el-input placeholder="请输入招生人数" v-model.number="activeData.plan" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="isShow = false">取消</el-button>
            <el-button type="primary" @click="dialogConfirm(formRef)">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, onMounted, onBeforeMount } from 'vue';
import { InitData, SchoolInfoListInt } from '@/types/admin/schoolInfo';
import {
  getSchoolInfo,
  deleteOneSchoolInfo,
  addOneSchoolInfo,
  editOneSchoolInfo,
} from '@/http/adminApi';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance } from 'element-plus';
import router from '@/router';

export default defineComponent({
  setup() {
    const data = reactive(new InitData());
    // const data = reactive({})

    const updateList = () => {

      data.infoTotalList = [];
      getSchoolInfo({
        enrollmentInfo: {
          profess: data.queryData.profess,
          schoolName: data.queryData.schoolName,
        },
        pageNum: data.currentPage,
        pageSize: data.pageSize,
      }).then(
        (res) => {
          data.totalNum = res.data.totalSize;
          data.infoTotalList = res.data.content;
        }
      ).catch(
        (err) => {

        }
      )
    };
    onBeforeMount(() => {
      const user = JSON.parse(localStorage.getItem('user'))
      console.log(user);

      if (user == null) {
        ElMessage.success('请先登录');
        router.push('/login')
      }
      else if (user.role == 0) {
        ElMessage.success('你只是普通用户');
        router.push('/display')
      }
    })

    onMounted(() => {
      updateList();
    });

    const currentChange = (page: number) => {
      // data.selectData.page = page;
      data.currentPage = page;
      data.selectData.schoolName = data.queryData.schoolName;
      data.selectData.profess = data.queryData.profess;
      // console.log(data.selectData.schoolName, data.selectData.profess);

      updateList();
    };

    const onQuery = () => {
      data.queryData.schoolName = data.selectData.schoolName;
      data.queryData.profess = data.selectData.profess;
      data.currentPage = 1;
      updateList();
    };

    const editInfo = (row: SchoolInfoListInt) => {
      console.log(row);
      data.isShow = true;
      data.status = 1;
      data.activeData = JSON.parse(JSON.stringify(row));
      data.activeDataPointer = row;
    };

    const deleteInfo = (row: SchoolInfoListInt) => {
      console.log(row);
      ElMessageBox.confirm(
        '这将会永久删除该信息，是否继续？',
        '删除该招生计划信息？',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          deleteOneSchoolInfo(row)
            .then(() => {
              data.infoTotalList.forEach((item, index, arr) => {
                if (item.id === row.id) {
                  arr.splice(index, 1);
                }
              });
              data.totalNum -= 1;
              ElMessage({
                type: 'success',
                message: '删除成功',
              });
            })
            .catch(() => {
              ElMessage({
                type: 'error',
                message: '删除失败',
              });
            });
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消删除',
          });
        });
    };

    const clearActive = () => {
      data.activeData.id = null;
      data.activeData.schoolCode = '';
      data.activeData.schoolName = '';
      data.activeData.province = '';
      data.activeData.majorCode = '';
      data.activeData.profess = '';
      data.activeData.subject = '';
      data.activeData.batch = null;
      data.activeData.plan = null;
    };

    const addInfo = () => {
      data.isShow = true;
      data.status = 0;
      clearActive();
      data.activeData.id = data.totalNum + 1;
    };

    const rules = {
      batch: [
        { required: true, message: '请输入录取批次' },
        { type: 'number', message: '录取批次为数字' },
      ],
      plan: [
        { required: true, message: '请输入招生人数' },
        { type: 'number', message: '招生人数为数字' },
      ],
      schoolCode: [{ required: true, message: '请输入学校代码' }],
      schoolName: [{ required: true, message: '请输入学校名称' }],
      province: [{ required: true, message: '请输入省份' }],
      majorCode: [{ required: true, message: '请输入专业代码' }],
      profess: [{ required: true, message: '请输入专业名称' }],
      subject: [{ required: true, message: '请输入专业类别' }],
    };

    const dialogConfirm = (formRef: FormInstance) => {
      // console.log('hi');
      // data.isShow = false;
      // console.log(data.activeData);
      formRef.validate((valid: boolean) => {
        if (valid) {
          data.isLoading = true;
          if (data.status === 0) {
            console.log('add');
            addOneSchoolInfo(data.activeData)
              .then((res) => {
                console.log(res);
                ElMessage.success('添加成功');
                data.isLoading = false;
                data.isShow = false;
                data.currentPage = 1;
                data.queryData.profess = data.queryData.schoolName = null;
                updateList();
              })
              .catch((err) => {
                console.log(err);
                ElMessage.error('添加失败');
                data.isLoading = false;
              });
          } else if (data.status === 1) {
            console.log('edit');
            editOneSchoolInfo(data.activeData)
              .then((res) => {
                console.log(res);
                ElMessage.success('编辑成功');
                for (let key in data.activeData)
                  data.activeDataPointer[key] = data.activeData[key];
                data.isLoading = false;
                data.isShow = false;
              })
              .catch((err) => {
                console.log(err);
                ElMessage.error('编辑失败');
                data.isLoading = false;
              });
          }
        } else {
          ElMessage.error('内容有错误！');
        }
      });
    };

    return {
      ...toRefs(data),
      onMounted,
      currentChange,
      onQuery,
      editInfo,
      deleteInfo,
      dialogConfirm,
      addInfo,
      rules,
    };
  },
});
</script>

<style scoped>
.pagination {
  float: right;
  margin-top: 10px;
}
</style>
